package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeItemService;
import com.jzo2o.foundations.service.IServeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author mr.wu
 * @since 2025-09-07
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {


    /**
     * 服务分页查询
     *
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> pageList(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> this.getBaseMapper().queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    @Autowired
    private IRegionService regionService;

    @Autowired
    private IServeItemService serveItemService;

    /**
     * 添加服务
     *
     * @param dtoList
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchAdd(List<ServeUpsertReqDTO> dtoList) {

        dtoList.forEach(x-> {
            //1.判断区域是否存在
            Region region = regionService.getById(x.getRegionId());
            if(region==null) {
                throw new ForbiddenOperationException("区域不存在");
            }

            //2.判断服务项是否存在
            ServeItem item = serveItemService.getById(x.getServeItemId());
            if(item==null) {
                throw new ForbiddenOperationException("服务项不存在");
            }

            //3.判断服务项是否已启用
            if(item.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()) {
                throw new ForbiddenOperationException("服务项未启用");
            }

            //4.判断服务项是否已添加过
            Integer count = this.lambdaQuery().eq(Serve::getRegionId, x.getRegionId())
                    .eq(Serve::getServeItemId, x.getServeItemId())
                    .count();
            if(count>0) {
                throw new ForbiddenOperationException("服务项无需重复添加");
            }

            //5.构建Serve对象
            Serve serve = BeanUtil.toBean(x, Serve.class);
            serve.setCityCode(region.getCityCode());

            //6.新增服务数据
            boolean result = this.save(serve);
            if(!result) {
                throw new DBException("新增服务失败");
            }
        });
    }


    /**
     * 修改服务价格
     *
     * @param id
     * @param price
     */
    @Override
    public void updatePirce(Long id, BigDecimal price) {
        //1. 判断服务是否存在
        Serve serve = this.getById(id);
        if(serve==null) {
            throw new BadRequestException("服务不存在");
        }

        //2. 判断服务是否已上架
        if(serve.getSaleStatus()==FoundationStatusEnum.ENABLE.getStatus()) {
            throw new BadRequestException("服务已上架无法修改");
        }

        //3. 修改服务价格   update serve set price=? where id=?
        boolean result = this.lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if(!result) {
            throw new DBException("修改服务价格失败");
        }
    }


    /**
     * 服务上架
     *
     * @param id
     */
    @Override
    public void onSale(Long id) {
        //1.判断服务是否存在
        Serve serve = this.getById(id);
        if(serve==null) {
            throw new BadRequestException("服务不存在");
        }

        //2. 判断服务是否已上架
        if(serve.getSaleStatus()==FoundationStatusEnum.ENABLE.getStatus()) {
            throw new BadRequestException("无需重复上架");
        }

        //3.判断服务关联的区域是否存在
        Region region = regionService.getById(serve.getRegionId());
        if(region==null) {
            throw new BadRequestException("区域不存在");
        }

        //4.判断服务关联的服务项是否存在
        ServeItem item = serveItemService.getById(serve.getServeItemId());
        if(item==null) {
            throw new BadRequestException("服务项不存在");
        }

        //5.判断服务关联的服务项是否已启用
        if(item.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()) {
            throw new BadRequestException("服务项未启用");
        }

        //6.更新服务状态为已上架
        boolean result = this.lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!result) {
            throw new DBException("设置服务上架失败");
        }
    }

    /**
     * 服务设置热门/取消
     *
     * @param id   服务id
     * @param flag 是否为热门，0：非热门，1：热门
     */
    @Override
    @Transactional
    public void changeHotStatus(Long id, Integer flag) {
        //1.判断服务是否存在
        Serve serve = this.getById(id);
        if(serve==null){
            throw new BadRequestException("服务不存在");
        }

        //2.判断是否有区域
        if(serve.getRegionId()==null){
            throw new BadRequestException("未选择区域");
        }

        //3.判断服务是否上架过
        if(serve.getSaleStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new BadRequestException("服务未上架");
        }

        //4.更新为是否热门
        boolean result = this.lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, flag)
                .set(Serve::getHotTimeStamp, System.currentTimeMillis())
                .update();
        if(!result) {
            throw new DBException("操作失败");
        }
    }

    /**
     * 删除服务
     *
     * @param id 服务id
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        //1.判断服务是否存在
        Serve serve = this.getById(id);
        if(serve==null){
            throw new BadRequestException("服务不存在");
        }

        //2.判断是否草稿状态
        if (serve.getSaleStatus()!=FoundationStatusEnum.INIT.getStatus()) {
            throw new BadRequestException("草稿状态方可删除");
        }

        //3.删除服务
        boolean result = this.removeById(id);
        if(!result){
            throw new DBException("删除服务失败");
        }

    }

    /**
     * 下架
     *
     * @param id         服务id
     */
    @Override
    @Transactional
    public void offSale(Long id){
        //1.判断服务是否存在
        Serve serve = this.getById(id);
        if(serve==null){
            throw new BadRequestException("服务不存在");
        }

        //2.判断是否有区域
        if(serve.getRegionId()==null){
            throw new BadRequestException("未选择区域");
        }

        //3.判断服务是否上架过
        if(serve.getSaleStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new BadRequestException("服务未上架");
        }

        //4.根据ID更新状态为已下架
        boolean result = this.lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if(!result) {
            throw new DBException("服务下架失败");
        }
    }
}
